package com.loongtech.bi.action.advertisment;

import com.loongtech.bi.action.PageHelper;
import com.loongtech.bi.action.UIHelper;
import com.loongtech.bi.advertisment.controller.BaseAdvAction;
import com.loongtech.bi.advertisment.model.ActiveTranData;
import com.loongtech.bi.advertisment.model.ActiveUrlTranData;
import com.loongtech.bi.advertisment.model.LTVData;
import com.loongtech.bi.advertisment.service.AdvDayDataAllService;
import com.loongtech.bi.advertisment.service.AdvDayDataService;
import com.loongtech.bi.entity.pay.EntityAdvNewUserLTV;
import com.loongtech.bi.entity.pay.EntityNewUserLTV;
import com.loongtech.bi.manager.system.SysUserManager;
import com.loongtech.bi.support.Helper;
import com.loongtech.core.util.Time;
import com.loongtech.core.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.*;

/**
 * ClassName: AdvDayAllDataAction
 *
 * @author liuchen
 * @Description: 市场数据分析 —— 广告日数据
 * @date 2017-03-28 下午2:23:49
 */
@Controller
@Scope("prototype")
@RequestMapping("/market/advDayAllDataMarket")
public class AdvDayAllDataBiAction extends BaseAdvAction {
    private static final long serialVersionUID = 1L;
    @Resource(name = "advDayDataAllService")
    private AdvDayDataAllService service;

    @Autowired
    private SysUserManager sysUserManager;
    @Resource(name = "advDayDataService")
    private AdvDayDataService urlService;

    @RequestMapping(value = "initParam.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void initParam(HttpServletRequest request, HttpServletResponse response, @RequestParam String uid, String callback) {
        try {
            Map<String, Object> result = new HashMap<String, Object>();
            Integer userid = sysUserManager.getUserIdByName(uid);
            if (null == userid) {
                result.put("res", 1);
                result.put("msg", "帐户错误，请联系管理员!");
                printToJson(response, result, callback);
                return;
            }
            initData(userid);

            result.put("res", "0");
            result.put("surl", getId());
            result.put("affiliation", getAffiliation());
            result.put("channelName", getChannelName());
            result.put("agent", getAgent());
            result.put("platform", getPlatform());
            result.put("paytype", getPaytype());
            result.put("advPosition", getAdvPosition());
            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
            return;
        }
    }

    private List<ActiveTranData> activeTranDatas;

    @RequestMapping(value = "search.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam String sday,
                       @RequestParam String eday, @RequestParam String agent, @RequestParam String platform,
                       @RequestParam String affiliation, @RequestParam String channelName, @RequestParam String paytype,
                       @RequestParam String advPosition, @RequestParam String uid, String callback) {
        try {
            Map<String, Object> result = new HashMap<String, Object>();
            Integer userid = sysUserManager.getUserIdByName(uid);
            if (null == userid) {
                result.put("res", 1);
                result.put("msg", "帐户错误，请联系管理员!");
                printToJson(response, result, callback);
                return;
            }
            initData(userid);

            if (hasAgents == null || hasAgents.size() <= 0) {
                result.put("res", "1");
                result.put("msg", "此用户无任何代理商权限，请联系管理员配置!");
                printToJson(response, result, callback);
                return;
            }

            String[] affiliations = "".equals(affiliation) ? getAffiliation().toArray(new String[getAffiliation().size()]) : Utils.matchesString(affiliation).split(",");
            String[] channelNames = "".equals(channelName) ? getChannelName().toArray(new String[getChannelName().size()]) : Utils.matchesString(channelName).split(",");
            String[] agents = "".equals(agent) ? getAgent().toArray(new String[getAgent().size()]) : Utils.matchesString(agent).split(",");
            String[] platforms = "".equals(platform) ? getPlatform().toArray(new String[getPlatform().size()]) : Utils.matchesString(platform).split(",");
            String[] paytypes = "".equals(paytype) ? getPaytype().toArray(new String[getPaytype().size()]) : Utils.matchesString(paytype).split(",");
            String[] advPositions = "".equals(advPosition) ? getAdvPosition().toArray(new String[getAdvPosition().size()]) : Utils.matchesString(advPosition).split(",");
            activeTranDatas = new ArrayList<>();
            activeTranDatas = service.getActiveTranDatas(sday, eday, affiliations, null, null, null,
                    paytypes, advPositions);
            System.out.println(agents.length + "   " + Arrays.toString(agents));
            result.put("res", "0");
            result.put("activeTranDatas", activeTranDatas);
            ActiveTranData data = getTotal(sday, eday, affiliations, channelNames, agents, platforms, paytypes,
                    advPositions);
            result.put("Totals", data);
            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
            return;
        }
    }

    @RequestMapping(value = "getLtv.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void searchLtv(HttpServletRequest request, HttpServletResponse response, @RequestParam String sday, @RequestParam String eday,
                          @RequestParam String uid, String callback) {
        try {
            Map<String, Object> result = new HashMap<>();
            Integer userid = sysUserManager.getUserIdByName(uid);
            if (null == userid) {
                result.put("res", 1);
                result.put("msg", "帐户错误，请联系管理员!");
                printToJson(response, result, callback);
                return;
            }
            initData(userid);

            if (hasAgents == null || hasAgents.size() <= 0) {
                result.put("res", "1");
                result.put("msg", "此用户无任何代理商权限，请联系管理员配置!");
                printToJson(response, result, callback);
                return;
            }
            String[] affiliations = getAffiliation().toArray(new String[getAffiliation().size()]);
            String[] channelNames = getChannelName().toArray(new String[getChannelName().size()]);
            String[] agents = getAgent().toArray(new String[getAgent().size()]);
            String[] platforms = getPlatform().toArray(new String[getPlatform().size()]);
            String[] paytypes = getPaytype().toArray(new String[getPaytype().size()]);
            String[] advPositions = getAdvPosition().toArray(new String[getAdvPosition().size()]);
            List<ActiveTranData> activeTranDatasAll = service.getActiveTranDatas(sday, eday, affiliations, channelNames, agents, platforms,
                    paytypes, advPositions);
            List<EntityNewUserLTV> ltvPay = service.getLTVPay(sday, eday);
            ArrayList<LTVData> ltvData = computeLTV(activeTranDatasAll, ltvPay);
            result.put("res", "0");
            result.put("ltvDate", ltvData);
            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
            return;
        }
    }

    private ArrayList<LTVData> computeLTV(List<ActiveTranData> activeTranDatas, List<EntityNewUserLTV> ltvPay) {
        Map<String, LTVData> ltvDataMap = new HashMap<>(16);
        if (!Helper.isEmptyValue(activeTranDatas)) {
            for (ActiveTranData o : activeTranDatas) {
                String key = o.getDateStr();
                LTVData tmp = ltvDataMap.get(key);
                if (tmp == null) {
                    tmp = new LTVData();
                    tmp.setDateStr(o.getDateStr());
                    ltvDataMap.put(key, tmp);
                }
                tmp.setChannelName(o.getChannelName());
                tmp.setActEquipment(o.getActEquipment());
                tmp.setNewAccount(o.getNewAccount());
                tmp.setPayrate(o.getPayrate());
                tmp.setNewPayUser(o.getNewPayUser());

                int d = Time.getInterval(Time.formatDate(o.getDateStr(), Time.TIMEPATTERN_SIMPLE), new Date());
                tmp.setTheLtvNewUser(d, o.getNewAccount());
            }
        }
        if (!Helper.isEmptyValue(ltvPay)) {
            for (EntityNewUserLTV o : ltvPay) {
                int d = Time.getInterval(Time.formatDate(o.getStartday(), "yyyy-MM-dd"), Time.formatDate(o.getEndday(), "yyyy-MM-dd"));  // 充值日与创建日相差天数
                if (d == 0 || d == 1 || d == 2 || d == 6 || d == 13 || d == 29 || d == 59 || d == 89 || d == 119 || d == 149 || d == 179) {
                    String key = o.getStartday();
                    LTVData tmp = ltvDataMap.get(key);
                    if (tmp == null) {
                      continue;
                    }
                    tmp.setThePay(d, UIHelper.getYuan(o.getCashadd()));
                    tmp.setTheLTV(d, UIHelper.getYuan(o.getCashadd()));
                }
            }
        }

        ArrayList<LTVData> ltvDate = new ArrayList<>(ltvDataMap.values());
        Collections.sort(ltvDate, new Comparator<LTVData>() {
            @Override
            public int compare(LTVData o1, LTVData o2) {
                return o2.getDateStr().compareTo(o1.getDateStr());
            }
        });
        return ltvDate;
    }

    public ActiveTranData getTotal(String sday, String eday, String[] affiliation, String[] channelName,
                                   String[] agent, String[] platform, String[] paytype, String[] advPosition) {
        ActiveTranData data = new ActiveTranData();
        data.setDateStr("Totals");
        data.setClkEquipment(getSumClkEquipment());
        data.setActEquipment(getSumActEquipment());
        data.setNewActive(getSumNewActive());
        data.setNewEquipment(getSumNewEquipment());
        data.setNewAccount(getSumNewAccount());
        data.setNewPay(getSumNewPay());
        data.setPayrate(Double.valueOf(getSumPayrate()));
        data.setNum(getSumNum());
        data.setTpr(Double.valueOf(getSumTpr()));
        data.setDiscount(getSumDiscount());
        data.setCpa(Double.valueOf(getSumCpa()));
        data.setTotalpay(getSumTotalpay());
        data.setRoi(Double.valueOf(getSumRoi(sday, eday, affiliation, channelName, agent, platform, paytype,
                advPosition)));
        return data;
    }


    @RequestMapping(value = "getLtvByUrl.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void searchLtvByUrl(HttpServletRequest request, HttpServletResponse response, @RequestParam String sday,
                               @RequestParam String eday, @RequestParam String uid, String callback) {
        try {
            Map<String, Object> result = new HashMap<>(16);
            Integer userid = sysUserManager.getUserIdByName(uid);
            if (null == userid) {
                result.put("res", 1);
                result.put("msg", "帐户错误，请联系管理员!");
                printToJson(response, result, callback);
                return;
            }
            initData(userid);

            if (hasAgents == null || hasAgents.size() <= 0) {
                result.put("res", "1");
                result.put("msg", "此用户无任何代理商权限，请联系管理员配置!");
                printToJson(response, result, callback);
                return;
            }
            String[] affiliations = getAffiliation().toArray(new String[getAffiliation().size()]);
            String[] channelNames = getChannelName().toArray(new String[getChannelName().size()]);
            String[] agents = getAgent().toArray(new String[getAgent().size()]);
            String[] platforms = getPlatform().toArray(new String[getPlatform().size()]);
            String[] paytypes = getPaytype().toArray(new String[getPaytype().size()]);
            String[] advPositions = getAdvPosition().toArray(new String[getAdvPosition().size()]);


            List<ActiveUrlTranData> activeTranDatasAll = urlService.getActiveTranDatas(sday, eday, affiliations, channelNames, agents, platforms,
                    paytypes, advPositions);
            List<EntityAdvNewUserLTV> ltvPay = urlService.getLTVPay(sday, eday, affiliations, channelNames, agents, platforms,
                    paytypes, advPositions);
            ArrayList<LTVData> ltvData = computeLTVUrl(activeTranDatasAll, ltvPay);
            result.put("res", "0");
            result.put("ltvDate", ltvData);
            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>(16);
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
        }
    }

    private ArrayList<LTVData> computeLTVUrl(List<ActiveUrlTranData> activeTranDatas, List<EntityAdvNewUserLTV> ltvPay) {
        Map<String, LTVData> ltvDataMap = new HashMap<>(16);
        if (!Helper.isEmptyValue(activeTranDatas)) {
            for (ActiveUrlTranData o : activeTranDatas) {
                String key = o.getKey();
                LTVData tmp = ltvDataMap.get(key);
                if (tmp == null) {
                    tmp = new LTVData();
                    tmp.setChannelName(o.getChannelName());
                    tmp.setAgent(o.getAgent());
                    tmp.setUrl(o.getUrl());
                    tmp.setDateStr(o.getDateStr());
                    ltvDataMap.put(key, tmp);
                }
                tmp.setActEquipment(o.getActEquipment());
                tmp.setNewAccount(o.getNewAccount());
                tmp.setPayrate(o.getNewAccount() == 0 ? 0 : PageHelper.floatKeepTwoNumber((double) o.getNewPayUser() / o.getNewAccount()));
                tmp.setNewPayUser(o.getNewPayUser());

                int d = Time.getInterval(Time.formatDate(o.getDateStr(), Time.TIMEPATTERN_SIMPLE), new Date());
                tmp.setTheLtvNewUser(d, o.getNewAccount());
            }
        }
        if (!Helper.isEmptyValue(ltvPay)) {
            for (EntityAdvNewUserLTV o : ltvPay) {
                // 充值日与创建日相差天数
                int d = Time.getInterval(Time.formatDate(o.getStartday(), "yyyy-MM-dd"), Time.formatDate(o.getEndday(), "yyyy-MM-dd"));
                if (d == 0 || d == 1 || d == 2 || d == 6 || d == 13 || d == 29 || d == 59 || d == 89 || d == 119 || d == 149 || d == 179) {
                    String key = o.getKey();
                    LTVData tmp = ltvDataMap.get(key);
                    if (tmp == null) {
                      continue;
                    }
                    tmp.setThePay(d, UIHelper.getYuan(o.getCashadd()));
                    tmp.setTheLTV(d, UIHelper.getYuan(o.getCashadd()));
                }
            }
        }

        ArrayList<LTVData> ltvDate = new ArrayList<>(ltvDataMap.values());
        Collections.sort(ltvDate, new Comparator<LTVData>() {
            @Override
            public int compare(LTVData o1, LTVData o2) {
                return o2.getDateStr().compareTo(o1.getDateStr());
            }
        });
        return ltvDate;
    }

    @RequestMapping(value = "getLtvByAgent.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void searchLtvByAgent(HttpServletRequest request, HttpServletResponse response, @RequestParam String sday,
                                 @RequestParam String eday, @RequestParam String uid, String callback) {
        try {
            Map<String, Object> result = new HashMap<>(16);
            Integer userid = sysUserManager.getUserIdByName(uid);
            if (null == userid) {
                result.put("res", 1);
                result.put("msg", "帐户错误，请联系管理员!");
                printToJson(response, result, callback);
                return;
            }
            initData(userid);

            if (hasAgents == null || hasAgents.size() <= 0) {
                result.put("res", "1");
                result.put("msg", "此用户无任何代理商权限，请联系管理员配置!");
                printToJson(response, result, callback);
                return;
            }
            String[] affiliations = getAffiliation().toArray(new String[getAffiliation().size()]);
            String[] channelNames = getChannelName().toArray(new String[getChannelName().size()]);
            String[] agents = getAgent().toArray(new String[getAgent().size()]);
            String[] platforms = getPlatform().toArray(new String[getPlatform().size()]);
            String[] paytypes = getPaytype().toArray(new String[getPaytype().size()]);
            String[] advPositions = getAdvPosition().toArray(new String[getAdvPosition().size()]);

            List<ActiveUrlTranData> activeTranDatasAll = urlService.getActiveTranDatasByAgent(sday, eday, affiliations, channelNames, agents, platforms,
                    paytypes, advPositions);
            List<EntityAdvNewUserLTV> ltvPay = urlService.getLTVPayByAgent(sday, eday, affiliations, channelNames, agents, platforms,
                    paytypes, advPositions);
            ArrayList<LTVData> ltvData = computeLTVAgent(activeTranDatasAll, ltvPay);
            result.put("res", "0");
            result.put("agentltvDate", ltvData);
            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>(16);
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
        }
    }

    private ArrayList<LTVData> computeLTVAgent(List<ActiveUrlTranData> activeTranDatas, List<EntityAdvNewUserLTV> ltvPay) {
        Map<String, LTVData> ltvDataMap = new HashMap<>(16);
        if (!Helper.isEmptyValue(activeTranDatas)) {
            for (ActiveUrlTranData o : activeTranDatas) {
                String key = o.getDateStr() + "-" + o.getAgent();
                LTVData tmp = ltvDataMap.get(key);
                if (tmp == null) {
                    tmp = new LTVData();
                    tmp.setDateStr(o.getDateStr());
                    tmp.setAgent(o.getAgent());
                    ltvDataMap.put(key, tmp);
                }
                tmp.setActEquipment(o.getActEquipment());
                tmp.setNewAccount(o.getNewAccount());
                tmp.setPayrate(o.getNewAccount() == 0 ? 0 : PageHelper.floatKeepTwoNumber((double) o.getNewPayUser() / o.getNewAccount()));
                tmp.setNewPayUser(o.getNewPayUser());

                int d = Time.getInterval(Time.formatDate(o.getDateStr(), Time.TIMEPATTERN_SIMPLE), new Date());
                tmp.setTheLtvNewUser(d, o.getNewAccount());
            }
        }
        if (!Helper.isEmptyValue(ltvPay)) {
            for (EntityAdvNewUserLTV o : ltvPay) {
                // 充值日与创建日相差天数
                int d = Time.getInterval(Time.formatDate(o.getStartday(), "yyyy-MM-dd"), Time.formatDate(o.getEndday(), "yyyy-MM-dd"));
                if (d == 0 || d == 1 || d == 2 || d == 6 || d == 13 || d == 29 || d == 59 || d == 89 || d == 119 || d == 149 || d == 179) {
                    String key = o.getStartday() + "-" + o.getAgent();
                    LTVData tmp = ltvDataMap.get(key);
                    if (tmp == null) {
                      continue;
                    }
                    tmp.setThePay(d, UIHelper.getYuan(o.getCashadd()));
                    tmp.setTheLTV(d, UIHelper.getYuan(o.getCashadd()));
                }
            }
        }

        ArrayList<LTVData> ltvDate = new ArrayList<>(ltvDataMap.values());
        Collections.sort(ltvDate, new Comparator<LTVData>() {
            @Override
            public int compare(LTVData o1, LTVData o2) {
                return o2.getDateStr().compareTo(o1.getDateStr());
            }
        });
        return ltvDate;
    }

    @RequestMapping(value = "getLtvByChannel.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void searchLtvByChannel(HttpServletRequest request, HttpServletResponse response, @RequestParam String sday,
                                   @RequestParam String eday, @RequestParam String uid, String callback) {
        try {
            Map<String, Object> result = new HashMap<>(16);
            Integer userid = sysUserManager.getUserIdByName(uid);
            if (null == userid) {
                result.put("res", 1);
                result.put("msg", "帐户错误，请联系管理员!");
                printToJson(response, result, callback);
                return;
            }
            initData(userid);

            if (hasAgents == null || hasAgents.size() <= 0) {
                result.put("res", "1");
                result.put("msg", "此用户无任何代理商权限，请联系管理员配置!");
                printToJson(response, result, callback);
                return;
            }
            String[] affiliations = getAffiliation().toArray(new String[getAffiliation().size()]);
            String[] channelNames = getChannelName().toArray(new String[getChannelName().size()]);
            String[] agents = getAgent().toArray(new String[getAgent().size()]);
            String[] platforms = getPlatform().toArray(new String[getPlatform().size()]);
            String[] paytypes = getPaytype().toArray(new String[getPaytype().size()]);
            String[] advPositions = getAdvPosition().toArray(new String[getAdvPosition().size()]);

            List<ActiveUrlTranData> activeTranDatasAll = urlService.getActiveTranDatasByChannel(sday, eday, affiliations, channelNames, agents, platforms,
                    paytypes, advPositions);
            List<EntityAdvNewUserLTV> ltvPay = urlService.getLTVPayByChannel(sday, eday, affiliations, channelNames, agents, platforms,
                    paytypes, advPositions);
            ArrayList<LTVData> ltvData = computeLTVChannel(activeTranDatasAll, ltvPay);
            result.put("res", "0");
            result.put("channelltvDate", ltvData);
            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>(16);
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
        }
    }

    private ArrayList<LTVData> computeLTVChannel(List<ActiveUrlTranData> activeTranDatas, List<EntityAdvNewUserLTV> ltvPay) {
        Map<String, LTVData> ltvDataMap = new HashMap<>(16);
        if (!Helper.isEmptyValue(activeTranDatas)) {
            for (ActiveUrlTranData o : activeTranDatas) {
                String key = o.getDateStr() + "-" + o.getChannelName();
                LTVData tmp = ltvDataMap.get(key);
                if (tmp == null) {
                    tmp = new LTVData();
                    tmp.setDateStr(o.getDateStr());
                    tmp.setChannelName(o.getChannelName());
                    ltvDataMap.put(key, tmp);
                }
                tmp.setActEquipment(o.getActEquipment());
                tmp.setNewAccount(o.getNewAccount());
                tmp.setPayrate(o.getNewAccount() == 0 ? 0 : PageHelper.floatKeepTwoNumber(o.getNewPayUser().doubleValue() / o.getNewAccount()));
                tmp.setNewPayUser(o.getNewPayUser());
                int d = Time.getInterval(Time.formatDate(o.getDateStr(), Time.TIMEPATTERN_SIMPLE), new Date());
                tmp.setTheLtvNewUser(d, o.getNewAccount());
            }
        }
        if (!Helper.isEmptyValue(ltvPay)) {
            for (EntityAdvNewUserLTV o : ltvPay) {
                // 充值日与创建日相差天数
                int d = Time.getInterval(Time.formatDate(o.getStartday(), "yyyy-MM-dd"), Time.formatDate(o.getEndday(), "yyyy-MM-dd"));
                if (d == 0 || d == 1 || d == 2 || d == 6 || d == 13 || d == 29 || d == 59 || d == 89 || d == 119 || d == 149 || d == 179) {
                    String key = o.getStartday() + "-" + o.getChannelName();
                    LTVData tmp = ltvDataMap.get(key);
                    if (tmp == null) {
                       continue;
                    }
                    tmp.setThePay(d, UIHelper.getYuan(o.getCashadd()));
                    tmp.setTheLTV(d, UIHelper.getYuan(o.getCashadd()));
                }
            }
        }

        ArrayList<LTVData> ltvDate = new ArrayList<>(ltvDataMap.values());
        Collections.sort(ltvDate, new Comparator<LTVData>() {
            @Override
            public int compare(LTVData o1, LTVData o2) {
                return o2.getDateStr().compareTo(o1.getDateStr());
            }
        });
        return ltvDate;
    }


    private Integer getSumClkEquipment() {
        int total = 0;
        for (ActiveTranData a : activeTranDatas) {
            total += a.getClkEquipment();
        }
        return total;
    }

    private Integer getSumActEquipment() {
        int total = 0;
        for (ActiveTranData a : activeTranDatas) {
            total += a.getActEquipment();
        }
        return total;
    }

    private Integer getSumNewActive() {
        int total = 0;
        for (ActiveTranData a : activeTranDatas) {
            total += a.getNewActive();
        }
        return total;
    }

    private Integer getSumNewEquipment() {
        int total = 0;
        for (ActiveTranData a : activeTranDatas) {
            total += a.getNewEquipment();
        }
        return total;
    }

    private Integer getSumNewAccount() {
        int total = 0;
        for (ActiveTranData a : activeTranDatas) {
            total += a.getNewAccount();
        }
        return total;
    }

    private Integer getSumNewPay() {
        int total = 0;
        for (ActiveTranData a : activeTranDatas) {
            total += a.getNewPay();
        }
        return total;
    }

    private String getSumPayrate() {
        DecimalFormat df = new DecimalFormat("#.##");
        int totalPayUser = 0;
        int totalNewUser = 0;
        for (ActiveTranData a : activeTranDatas) {
            totalPayUser += a.getNewPayUser();
            totalNewUser += a.getNewAccount();
        }
        return totalNewUser != 0 ? df.format((double) totalPayUser / totalNewUser) : "0";
    }

    private Integer getSumNum() {
        int total = 0;
        for (ActiveTranData a : activeTranDatas) {
            total += a.getNum();
        }
        return total;
    }

    private String getSumTpr() {
        DecimalFormat df = new DecimalFormat("#.##");
        int sumNewAccount = getSumNewAccount();
        return sumNewAccount != 0 ? df.format((double) getSumNum() / sumNewAccount) : "0";
    }

    private Integer getSumDiscount() {
        Integer total = 0;
        for (ActiveTranData a : activeTranDatas) {
            total += a.getDiscount();
        }
        return total;
    }

    private String getSumCpa() {
        DecimalFormat df = new DecimalFormat("#.##");
        double totalDiscount = 0.0;
        int totalNewUser = 0;
        for (ActiveTranData a : activeTranDatas) {
            totalDiscount += a.getDiscount();
            totalNewUser += a.getNewAccount();
        }
        return totalNewUser != 0 ? df.format((double) totalDiscount / totalNewUser) : "0";
    }

    private int getSumTotalpay() {
        int totalpay = 0;
        for (ActiveTranData a : activeTranDatas) {
            totalpay += a.getTotalpay();
        }
        return totalpay;
    }

    private String getSumRoi(String sday, String eday, String[] affiliation, String[] channelName, String[] agent,
                             String[] platform, String[] paytype, String[] advPosition) {
        DecimalFormat df = new DecimalFormat("#.##");
        Integer total = 0;
        for (ActiveTranData a : activeTranDatas) {
            total += a.getDiscount();
        }
        Integer roi = 0;
        try {
            roi = service.getAllRoi(sday, eday, affiliation, channelName, agent, platform, paytype, advPosition);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return total != 0 ? df.format((double) roi * 100 / total) : "0";
    }
}
